<?php
namespace Home\Controller;

use Think\Controller;

class OrderController extends HomeController
{
    public function __construct()
    {
        parent::__construct();
        $this->assign('bottom',array('bottom','','',''));
    }

    public function index(){
        //登录检测
        hook('login','','true');

        trace($_POST);
        $uid = session("member.id");
        $Cart = D("Cart");
        $carts = $Cart->getCart($uid);
        $Goods = D("Goods");
        foreach($carts as &$v){
            $data = json_decode($v['cartdata'],true);
            trace($data,'data');
            $v['goods'] =   $Goods->getDetail($v['goods_id']);
        }
        dump($carts);
        //trace($carts,'carts');
        $this->assign('carts',$carts);
        $this->display();
    }

    //获取物流信息
    public function wuliu(){
        $id = I("id",0);
        $wuliu = get_order_wuliu($id);
        dump($wuliu);
    }

    //全部订单
    public function all(){
        //登录检测
        hook('login','','true');


        $user_id = session("member.id");
        $Order = D("Order");
        $orders = $Order->getOrder($user_id);
        foreach($orders as &$v){
            $data = json_decode($v['cartdata'],true);
            trace($data['item'],'data');
            foreach($data['item'] as $goods){
                if(isset($goods['tags'])) $goods["tags"] = json_decode($goods["tags"], true);
                $v['goods'][] =   $goods;
            }
        }unset($v);

        trace($orders,'orders');
        $this->assign('orders',$orders);
        $this->display('lists');
    }

    //待取货
    public function take(){
        //登录检测
        hook('login','','true');

        $user_id = session("member.id");
        $Order = D("Order");
        $map = array();
        $map['_string'] = '((pay_type=1 AND pay_status=1) AND ((deliver_type=1 AND deliver_status=1)OR(deliver_type=0 AND deliver_status=1)OR(deliver_type=0 AND deliver_status=0))) OR ((pay_type=0 AND pay_status=0)AND(pay_type=0 AND pay_status=0))';
        //$map['_string'] = '(`pay_type`=1 AND `pay_status`=1) AND ((`deliver_type`=1 AND `deliver_status`=1)OR(`deliver_type`=0 AND `deliver_status`=1)OR(`deliver_type`=0 AND `deliver_status`=0))';
        $orders = $Order->getOrder($user_id,$map);
        trace($Order->getLastSql(),'sql');
        foreach($orders as &$v){
            $data = json_decode($v['cartdata'],true);
            trace($data['item'],'data');
            foreach($data['item'] as $goods){
                $v['goods'][] =   $goods;
            }
        }
        trace($orders,'orders');
        $this->assign('orders',$orders);

        $this->assign('bottom',array('','','','bottom',''));
        $this->display('lists');
    }

    //待发货
    public function deliver(){
        //登录检测
        hook('login','','true');

        $user_id = session("member.id");
        $Order = D("Order");
        $map = array(
            'pay_type'    =>  1,
            'pay_status'  =>  1,
            'deliver_type'=>1,
            'deliver_status'=>0,
            'status'=>1,
        );
        trace($map,'map');
        $orders = $Order->getOrder($user_id,$map);
        foreach($orders as &$v){
            $data = json_decode($v['cartdata'],true);
            trace($data['item'],'data');
            foreach($data['item'] as $goods){
                $v['goods'][] =   $goods;
            }
        }
        trace($orders,'orders');
        $this->assign('orders',$orders);


        $this->assign('bottom',array('','','bottom','',''));
        $this->display('lists');
    }


    //待付款
    public function payment(){
        //登录检测
        hook('login','','true');


        $user_id = session("member.id");
        $Order = D("Order");
        $map = array(
            'pay_type'=>1,
            'pay_status'=>0
        );
        $orders = $Order->getOrder($user_id,$map);
        foreach($orders as &$v){
            $data = json_decode($v['cartdata'],true);
            trace($data['item'],'data');
            foreach($data['item'] as $goods){
                $v['goods'][] =   $goods;
            }
        }
        trace($orders,'orders');
        $this->assign('orders',$orders);

        $this->assign('bottom',array('','bottom','',''));
        $this->display('lists');
    }


    //    退款
    public function refund(){
        //登录检测
        hook('login','','true');

        $user_id = session("member.id");
        $Order = D("Order");
        $map = array(
            'pay_type'=>1,
            'pay_status'=>array('gt',0),
            'status'=>array('in',array(3,4))
        );
        $orders = $Order->getOrder($user_id,$map);
        foreach($orders as &$v){
            $data = json_decode($v['cartdata'],true);
            trace($data['item'],'data');
            foreach($data['item'] as $goods){
                $v['goods'][] =   $goods;
            }
        }
        trace($orders,'orders');
        $this->assign('orders',$orders);

        $this->assign('bottom',array('','','','','bottom'));
        $this->display('lists');
    }

    //详细信息
    public function detail(){
        //登录检测
        hook('login','','true');

        $id = I('get.id',0);
        $Order = D("Order");

        //获取订单详情
        $info = $Order->find($id);
        $info['cartdata'] = json_decode($info['cartdata'],true);

//        dump($info);

        foreach($info['cartdata']['item'] as $goods){
            if(isset($goods['tags'])) $goods["tags"] = json_decode($goods["tags"], true);
            $info['goods'][] =   $goods;
        }

//        dump($info);
        trace($info,'info');

        //获取物流详情
        $wuliu = get_order_wuliu($id);
        $this->assign('wuliu',$wuliu);

        $this->assign("info",$info);
        $this->display();
    }

    public function address(){
        //登录检测
        hook('login','','true');

        $Address    =   D("Address");
        $lists  =   $Address->getAddress(session("member.id"));
        trace($lists,'lists');
        trace(session("member"),'member');

        $this->assign('lists',$lists);
        $this->display();
    }
    
    /**
     * 删除收货地址
     */
    public function address_del() {
        $id = I('get.id','','intval');
        $msg = D('address')->delete($id);
        if(!empty($msg)) {
            $this->success('删除成功！');
        } else {
            $this->success('删除失败！');
        }
    }

    public function confirm(){
        //登录检测
        hook('login','','true');
        $uid = session("member.id");


//        echo '原始post';dump($_REQUEST);die();
        //防止引号被实体化
        $tags      = $_POST['tags'];
        $_POST = I("param.");
        $_POST['tags'] = $tags;
//        echo 'I过滤后post';dump($_POST);


        //对商品订单的库存检测等
        $_POST = hook("confirm",$_POST);
//        echo '插件处理的post';dump($_POST);
        


        /*
         * 接收购物车ID，也可能创建临时购物车并返回ID
         */
        if(I("get.direct",'no') == 'yes'){
            //直接购买，对商品进行活动处理，购物车id不应存在，直接生成临时购物车，只有一个商品，缓存购物车id


            //获取属性
            //$attr = session("attribute");  暂时
            $attr  = json_decode($_POST['attribute'],true);
//            session("attribute",$attr);
            $this->assign("attribute",$attr);

            //构建购物车数据
            $data = array(
                'user_id'=>session("member.id"),
                'goods_id'  =>  I("post.goods_id"),
                'goods_title'=>I("post.goods_title"),
                'price' =>  $_POST['price'],
                'origin_price' =>  $_POST['origin_price'],
                'number'    =>   $_POST['number'],
                'attribute' => $_POST['attribute'],
                'status'=>2,//临时购物车
                'activity'=>$_POST['activity'],
                'tags'=>$_POST['tags']
            );
//            echo '临时购物车数据';dump($data);

            if(empty($data['goods_id']) || empty($data['user_id']) || empty($data['price']) || empty($data['number'])){

                $this->alert("可能商品已售罄，可能未登录");
                return ;
            }else{

            }
//            echo '临时购物车数据';dump($data);

            trace($data,'data');
            $Cart = D("Cart");
//            if(($data=$Cart->create($data)) && ($cart_ids[] = $Cart->add($data))){
//                $carts[0] = $data;
//            }else {
//                $this->alert("商品有点问题 " . $Cart->getError());
//            }
            if(!($cart_ids[] = $Cart->confirm_update($data))){
                $this->alert('除了点状况 '.$Cart->getError());
                return ;
            }
//            echo '临时购物车返回结果';dump($cart_ids);
        }else{
            //购物车够买，获取购物车商品，若购物车中有活动商品，对其进行活动处理，此处理可能会执行减少活动库存等操作

            $cart_ids = $_POST['cart_id'];
            if(empty($cart_ids)){
//                session('cart_ids',$cart_ids);
                $this->alert("没选择商品吧？",U("Cart/index"),1);
                return ;
            }
//            elseif(!empty(session("cart_ids"))){
//                $cart_ids = session("cart_ids");
//            }

        }
        $this->assign("cart_ids",$cart_ids);


        //获取购物车详细数据
        if(count($cart_ids)>0 && ($carts=D("Cart")->getCartsById($cart_ids))){
            foreach($carts as &$v){
                if(empty($v['goods_id'])){
                    $this->alert("购物车中可能有失效的商品",U("Cart/index"),1);
                    return ;
                }
                $v['tags'] = json_decode($v['tags'], true);
                $v['goods'] =   D("Goods")->getDetail($v['goods_id']);
            }unset($v);
        }else{
            $this->alert("购物车中可能有失效的商品",U("Cart/index"),1);
            return;
        }
//        echo '购物车详细数据';dump($carts);



        //总价
        $total = get_total_price($carts);
//echo '总价'.$total;
        $this->assign('carts',$carts);
        $this->assign('total',$total);

        //获取地址
        $Address = D("Address");
        $address_id = $_POST['address_id'];
        trace("address_id ".$address_id);
        if($address_id>0){
            $address = $Address->getAddressById($address_id);
        }else{
            $address = $Address->getOne($uid);
        }

        trace($address,'address');
        $this->assign('address',$address);


        $this->display();
    }

    /**
     * @describe 订单生成
     * @author Creatint
     */
    public function add(){
        trace(session('member'),'member');
        $uid = session("member.id");
        if(!session('member')){
            $this->error('未登录',U("Login/index"));
        }

        $_POST = I("param.");
//        echo '原始post数据';dump($_POST);exit;


        //获取购物车数据
        if(!(empty($cart_id = $_POST['cart_id']))){
            $Cart = D("Cart");
            if(empty($carts = $Cart->getCartsById($cart_id))){
                $this->alert('结算商品已经没了，可能已经生成了订单',U("Cart/index"),1);
                return;
            }
        }else{
            $this->alert('没传过来购物车数据啊',U("Cart/index"),1);
            return ;
        }

        //减少库存
        hook("order",$cart_id);

        //获取购物车详情 计算总价格
        $Goods = D("Goods");
        $total_price = 0;
        foreach($carts as &$v){
            $goods = $Goods->getDetail($v['goods_id'],'multimage,title,price,stock');
            $total_price += $v['price']*$v['number'];
//            dump($goods);
//            trace($goods,'goods');
            $v['cover'] = explode(',',$goods['multimage'])[0];
            $v['title'] = $goods['title'];
            $v['count'] = $v['number'];
            $v['stock'] = $goods['stock'];  //库存
        }
        trace($carts,'cart');
        trace($total_price,'total_price');




        $data = array();
        $address_id = $_POST['address_id'];
        $address = M("Address")->where("id={$address_id}")->find();




        //订单数据生成
        //number
        $data['user_id'] = session('member.id');
        $data['user_name'] = session('member.username');
        $data['address'] = $address['address'];
        $data['mobile'] = $address['mobile'];

        $data['total_price'] = $total_price;
        $data['deliver_status'] = 0;

        $data['status'] = 1;

        trace($data,'data');



        $json['item'] = $carts;
        $json['address'] = $address;
        $json = json_encode($json);//'{"item":[{"id":1,"cover":12,"title":"\u8863\u54c1\u5929\u6210 2016\u79cb\u88c5\u65b0\u54c1\u7537\u88c5\u9488\u7ec7\u5f00\u886b \u97e9\u7248\u6761\u7eb9\u65f6\u5c1a\u9752\u5e74\u6bdb\u8863\u5916\u5957","price":178,"count":1},{"id":2,"cover":13,"title":"\u8863\u670d\u8863\u670d","price":100,"count":2}]}';

        $data['cartdata'] = $json;
        $Order = D("Order");


        if($order = $Order->update($data)){
            //TODO::创建订单成功，清空购物车
            $Cart->del($cart_id,$uid);
        }else{
            $this->error($Order->getError(),U('Center/order'));
        }
        trace($order,'order');
        if($order){
            redirect(U('Order/detail',array('id'=>$order['id'])));
        }

    }

    public function update(){
        $goods_id = I("goods_id",0);
        $number = I("number",1);
        $user_id = 6;
        $data = array(
            'user_id'=>$user_id,
            'goods_id'  =>  $goods_id,
            'number'    =>  $number
        );
        $Cart = D("Cart");
        if($Cart->update($data)){
            $this->success('添加成功');
        }else{
            $this->error('添加失败');
        }

    }

    //软删除订单
    public function delete($order_id){
        $data = array('id'=>$order_id,'status'=>0);
        $Order = D("Order");
        if($Order->save($data)){
            $this->alert('取消成功',U("Order/all"));
        }else{
            $this->alert('取消失败 '.$Order->getError(),U("Order/all"));
        }
    }

    //取消订单
    public function cancel($order_id){
        $data = array('id'=>$order_id,'status'=>0);
        $Order = D("Order");
        if($Order->save($data)){
            $this->success('取消成功');
        }else{
            $this->error('取消失败：'.$Order->getError());
        }
    }

    // 申请退款
    public function tuikuan($order_id){
        $data = array('id'=>$order_id,'status'=>3);
        $Order = D("Order");
        if($Order->save($data)){
            $this->alert('申请成功',$_SERVER['HTTP_REFERER']);
        }else{
            $this->alert('申请失败：'.$Order->getError());
        }
    }

    //确认收货
    public function queren($order_id){
        $data = array('id'=>$order_id,'status'=>2,'deliver_status'=>2);
        $Order = D("Order");
        if($Order->save($data)){
            $this->alert('确认成功',$_SERVER['HTTP_REFERER']);
        }else{
            $this->alert('确认失败：'.$Order->getError());
        }
    }


    /**
     * 提示跳转
     */
    public function alert($msg,$url,$time=-1) {
        $this->assign('info',array('msg'=>$msg,'url'=>$url));
        $this->assign("time",$time);
        $this->display('Notice/location');
    }
}
